package com.xiaoda.controller;

import com.xiaoda.entity.Article;
import com.xiaoda.entity.Comment;
import com.xiaoda.entity.JsonResult;
import com.xiaoda.entity.User;
import com.xiaoda.service.CommentService;
import com.xiaoda.service.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 评论管理
 */

@Controller
@CrossOrigin
@RequestMapping("/comment")
@ResponseBody
public class CommentController {

    @Autowired
    CommentService commentService;

    @Autowired
    LikeService likeService;

    /**
     * 获取评论列表
     *
     * @param fromUid 评论人
     * @return 评论列表
     */
    @GetMapping("/count")
    public JsonResult count(@RequestParam("fromUid") String fromUid) {
        JsonResult json = new JsonResult();
        List<Comment> list = commentService.findAllByUid(fromUid);
        if (list.isEmpty()) {
            json.setCode(404);
            json.setMsg("未查到发布的评论！！！");
        } else {
            getList(list);
            json.setCode(200);
            json.setMsg("查询发布的评论成功！！！");
        }
        json.setData(list);
        return json;
    }

    /**
     * 添加评论
     *
     * @param fromUid 评论人
     * @param toUid   评论对象
     * @param toAid   评论对象所属文章
     * @param toId    评论对象所属评论
     * @param content 评论内容
     * @return 评论对象
     * @throws IllegalAccessException 反射异常
     */
    @PostMapping("/add")
    public JsonResult add(@RequestParam("fromUid") String fromUid,
                          @RequestParam("toUid") String toUid,
                          @RequestParam("toAid") int toAid,
                          @RequestParam("toId") String toId,
                          @RequestParam("content") String content) throws IllegalAccessException {
        JsonResult json = new JsonResult();
        Comment c1 = new Comment();
        User u1 = new User();
        u1.setAccount(fromUid);
        c1.setFromUid(u1);
        User u2 = new User();
        u2.setAccount(toUid);
        c1.setToUid(u2);
        Article article = new Article();
        article.setId(toAid);
        c1.setToAid(article);
        Comment c2 = new Comment();
        if (toId != null && !toId.isEmpty()) {
            c2.setId(Integer.parseInt(toId));
        }
        c1.setToId(c2);
        c1.setContent(content);
        int row = commentService.addComment(c1);
        Comment c3 = commentService.findByIdFull(c1.getId());
        if (c3 != null) {
            c3.getFromUid().setPassword(null);
            c3.getToUid().setPassword(null);
        }
        if (row <= 0) {
            json.setCode(404);
            json.setMsg("评论失败！！！");
        } else {
            json.setCode(200);
            json.setMsg("评论成功！！！");
        }
        Map<String, Object> m = new HashMap<>();
        for (Field f : Comment.class.getDeclaredFields()) {
            f.setAccessible(true);
            m.put(f.getName(), f.get(c3));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Object createTIme = m.get("createTime");
        if (createTIme != null) {
            m.put("createTime", sdf.format(createTIme));
        }
        m.put("concerned", likeService.findByUid(fromUid, ((User) m.get("toUid")).getAccount()) != null);
        m.put("isOwn", ((User) m.get("fromUid")).getAccount().equals(fromUid));
        json.setData(m);
        return json;
    }

    /**
     * 获取文章评论列表
     *
     * @param id      文章 id
     * @param account 评论人
     * @return 评论列表
     * @throws IllegalAccessException 反射异常
     */
    @GetMapping("/all")
    public JsonResult all(@RequestParam("id") int id, @RequestParam("account") String account) throws IllegalAccessException {
        JsonResult json = new JsonResult();
        List<Comment> list = commentService.findAllComments(id);
        getList(list);
        List<Map<String, Object>> mlist = new ArrayList<>();
        for (Comment c : list) {
            Map<String, Object> map = new HashMap<>();
            for (Field f : Comment.class.getDeclaredFields()) {
                f.setAccessible(true);
                map.put(f.getName(), f.get(c));
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Object createTIme = map.get("createTime");
            if (createTIme != null) {
                map.put("createTime", sdf.format(createTIme));
            }

            map.put("concerned", likeService.findByUid(account, ((User) map.get("fromUid")).getAccount()) != null);
            map.put("isOwn", ((User) map.get("fromUid")).getAccount().equals(account));
            mlist.add(map);
        }
        if (list.isEmpty()) {
            json.setCode(404);
            json.setMsg("未查到发布的评论！！！");
        } else {
            json.setCode(200);
            json.setMsg("查询评论成功！！！");
        }
        Map<String, Object> m = new HashMap<>();
        m.put("list", mlist);
        m.put("total", commentService.commentArticleNum(id));
        json.setData(m);
        return json;
    }

    /**
     * 通过条件查询评论列表
     *
     * @param map 条件
     * @return 返回评论列表
     */
    @PostMapping("/keyword")
    public JsonResult keyword(@RequestBody Map<String, Object> map) {
        JsonResult json = new JsonResult();
        Map<String, Object> m = this.ListToStringInMap(map);
        List<Comment> list = commentService.searchComment(m);
        if (list.isEmpty()) {
            json.setCode(404);
            json.setMsg("未查到任一评论！！！");
        } else {
            json.setCode(200);
            json.setMsg("查询评论成功！！！");
        }
        json.setData(list);
        return json;
    }

    @GetMapping("/whole")
    public JsonResult whole() {
        JsonResult json = new JsonResult();
        List<Comment> list = commentService.findAll();
        if (list.isEmpty()) {
            json.setCode(404);
            json.setMsg("未查到任一评论！！！");
        } else {
            json.setCode(200);
            json.setMsg("评论查询成功！！！");
        }
        json.setData(list);
        return json;
    }

    @PutMapping("/update")
    public JsonResult update(@RequestBody Map<String, Object> map) {
        JsonResult json = new JsonResult();
        int row = commentService.updateComment(map);
        if (row > 0) {
            json.setCode(200);
            json.setMsg("评论更新成功！！！");
        } else {
            json.setCode(403);
            json.setMsg("评论更新失败！！！");
        }
        json.setData(null);
        return json;
    }

    @DeleteMapping("/delete/{id}")
    public JsonResult delete(@PathVariable("id") int id) {
        JsonResult json = new JsonResult();
        int row = commentService.deleteComment(id);
        if (row > 0) {
            json.setCode(200);
            json.setMsg("评论删除成功！！！");
        } else {
            json.setCode(403);
            json.setMsg("评论删除失败！！！");
        }
        json.setData(null);
        return json;
    }

    /**
     * 处理评论列表数据
     *
     * @param list 评论列表
     */
    public void getList(List<Comment> list) {
        for (Comment comment : list) {
            comment.getFromUid().setPassword(null);
            if (comment.getToUid() != null) comment.getToUid().setPassword(null);
            if (comment.getToId() != null) {
                Comment c = commentService.findByIdFull(comment.getToId().getId());
                c.getFromUid().setPassword(null);
                if (comment.getToUid() != null) comment.getToUid().setPassword(null);
                comment.setToId(c);
            }
        }
    }


    /**
     * 将 map 里的 List 转换为 String
     *
     * @param map 哪个 map 内的数据
     * @return 返回处理后的 map 集合
     */
    public Map<String, Object> ListToStringInMap(Map<String, Object> map) {
        Map<String, Object> m = new HashMap<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() instanceof List && !Objects.equals(entry.getKey(), "createTime")) {
                StringBuilder str = new StringBuilder();
                List<Object> list = (List<Object>) map.get(entry.getKey());
                for (int i = 0; i < list.size(); i++) {
                    str.append("'").append(list.get(i)).append("'");
                    if (i < list.size() - 1) {
                        str.append(",");
                    }
                }
                m.put(entry.getKey(), str.toString());
            } else {
                m.put(entry.getKey(), entry.getValue());
            }
        }
        return m;
    }

}
